package com.example.myapplication.ui.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myapplication.network.api.ProductApiService
import com.example.myapplication.network.api.User
import com.example.myapplication.network.api.UserApiService
import com.example.myapplication.network.core.NetworkResult
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class UserViewModel : ViewModel() {
    //对内私有的
    private val _users: MutableStateFlow<NetworkResult<List<User>>> = MutableStateFlow<NetworkResult<List<User>>>(NetworkResult.Loading())

    //对外公开给页面使用
    val users: StateFlow<NetworkResult<List<User>>> = _users.asStateFlow()

    //GET请求： 发起网络请求（获取所有User数据）
    fun getUsers(){
        viewModelScope.launch {
            //如果try里的代码出现异常，则会执行catch里面的语句
            _users.value = NetworkResult.Loading()
            try {
                val users: List<User> = UserApiService.getInstance().getUsers()
                _users.value = NetworkResult.Success(users)
            }catch (e: Exception){
                _users.value = NetworkResult.Error("网络异常，请求数据失败")
            }
        }
    }

    //POST请求
    fun postUser(){
        viewModelScope.launch {
            try {
                val user = User(id=12,"User12")
                UserApiService.getInstance().postUser(user)
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }

    //PUT请求
    fun putUser(){
        viewModelScope.launch {
            try {
                val user = User(id=3,name="wangwu")
                UserApiService.getInstance().putUser(user.id,user)
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }

    //DELETE请求
    fun deleteUser(){
        viewModelScope.launch {
            try {
                UserApiService.getInstance().deleteUser(4)
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }
}